#include "TcpServer.hpp"
#include "Http.hpp"

void Usage(const std::string& proc)
{
    std::cout << "Usage:\n\t" << proc << " <local_port>\n" << std::endl;
}

std::shared_ptr<HttpResponse> Login(std::shared_ptr<HttpRequest> req)
{
    LOG(DEBUG, "Handling /login request");
    
    std::string userdata;

    // 根据请求方法获取用户数据
    if (req->Method() == "GET")
    {
        userdata = req->Args();
    }
    else if (req->Method() == "POST")
    {
        userdata = req->Text();
    }

    LOG(DEBUG, "User data received: %s", userdata.c_str());

    // 构建应答
    auto response = Factory::BuildHttpResponse();
    response->AddStatusLine(200, "OK");
    response->AddHeader("Content-Type", "text/html");
    response->AddText("<html><h1>Data processed successfully</h1></html>");

    LOG(DEBUG, "Login handler completed");
    
    return response;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        return 1;
    }

    // 解析端口
    uint16_t port;
    try
    {
        port = static_cast<uint16_t>(std::stoi(argv[1]));
    }
    catch (const std::invalid_argument& e)
    {
        std::cerr << "Invalid port number: " << argv[1] << std::endl;
        return 1;
    }

    // 实例化HttpServer并设置路由处理
    HttpServer httpservice;
    httpservice.AddHandler("/login", Login);

    // 启动TcpServer并绑定HttpServer的请求处理函数
    TcpServer tcpsvr(port, std::bind(&HttpServer::HandleHttpRequest, &httpservice, std::placeholders::_1));
    
    LOG(INFO, "Server is starting on port: %d", port);
    
    // 开始事件循环
    tcpsvr.Loop();

    return 0;
}
